/*
 * @Author: wenqiang zhang
 * @Date: 2020-12-08 13:32:28
 * @LastEditTime: 2021-06-01 20:22:06
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /bridge-tunnel-ui/src/permission.js
 */
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken, getCookie, removeCookie } from '@/utils/auth'
import { LOGIN_TIME_OUT } from '@/utils/dict'
import Vue from 'vue'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect', '/bind', '/register']
let timer
router.beforeEach((to, from, next) => {
  NProgress.start()
  console.log('getCookie(uid)', getCookie('uid'))
  console.log('to.path', to.path)
  window.localStorage.setItem('tOut', LOGIN_TIME_OUT)
  if (getCookie('uid')) { // 登录
    if (to.path === '/main') { // 登录超时
      if (timer) {
        window.clearInterval(timer)
      }
      timer = window.setInterval(() => {
        let tOut = 0
        if (window.localStorage.getItem('tOut') || window.localStorage.getItem('tOut') == 0) {
          tOut = window.localStorage.getItem('tOut')
        }
        tOut--
        window.localStorage.setItem('tOut', tOut)
        if (window.localStorage.getItem('tOut') <= 0) {
          removeCookie('uid')
          removeCookie('token')
          next({ path: '/login' })
          const vue = new Vue()
          vue.msgInfo('登入已超时， 请重新登录。')
        }
      }, 1000)
    }
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      next()
      NProgress.done()
    }
  } else {
    // 没有token
    // if (whiteList.indexOf(to.path) !== -1) {
    //   // 在免登录白名单，直接进入
    //   next()
    // } else {
    //   next('/login') // 否则全部重定向到登录页
    //   NProgress.done()
    // }
    if (timer) { // 登录超时
      window.clearInterval(timer)
    }
    next()
  }
  // next()
})

router.afterEach(() => {
  NProgress.done()
})
